package com.wms.common.fusionchart.util;

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.wms.common.fusionchart.bean.Set;

public class DateConvertor {
	
	private Date start, end;
	
	private SimpleDateFormat dateformat=new SimpleDateFormat("HH");
	
	private int step=1, stepUnit=Calendar.HOUR;
	
	private String key="time";
	
	private List<String> values;
	
	public Map<String, List<Set>> convert(List<Map<String,Object>> data){
		Map<String, List<Set>> utils = new HashMap<String, List<Set>>();
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(end);
		calendar.add(Calendar.SECOND, 1);
		end = calendar.getTime();
		for(String value:values){
			List<Set> x = new ArrayList<Set>();
			
			calendar.setTime(start);
			Date temp=calendar.getTime();
			while(temp.before(end)){
				String label = dateformat.format(temp);
				Set s = new Set();
				s.setLabel(label);
				
				Map curMap = null;
				for(Map d:data){
					Timestamp t = (Timestamp)d.get(key);
					if(null==t) t=(Timestamp)d.get(key.toUpperCase());
					if(t.getTime()/1000 == temp.getTime()/1000){
						curMap = d;
						break;
					}
				}
				
				if(null!=curMap){
					if(null!=curMap.get(value)) {
						DecimalFormat df = new DecimalFormat("#.00");
						s.setValue(df.format(curMap.get(value)));
					}
				}
				x.add(s);
				
				calendar.setTime(temp);
				calendar.add(stepUnit, step);
				temp = calendar.getTime();
			}
			utils.put(value, x);
		}
		return utils;
	}
	
	public Date getStart() {
		return start;
	}

	public void setStart(Date start) {
		this.start = start;
	}

	public Date getEnd() {
		return end;
	}

	public void setEnd(Date end) {
		this.end = end;
	}

	public SimpleDateFormat getDateformat() {
		return dateformat;
	}

	public void setDateformat(SimpleDateFormat dateformat) {
		this.dateformat = dateformat;
	}

	public int getStep() {
		return step;
	}

	public void setStep(int step) {
		this.step = step;
	}

	public int getStepUnit() {
		return stepUnit;
	}

	public void setStepUnit(int stepUnit) {
		this.stepUnit = stepUnit;
	}

	public String getKey() {
		return key;
	}

	public void setKey(String key) {
		this.key = key;
	}

	public List<String> getValues() {
		return values;
	}

	public void setValues(List<String> values) {
		this.values = values;
	}
	
}
